package com.tianqu.tms.www.check.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code39Encoder;
import org.jbarcode.encode.EAN13Encoder;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WideRatioCodedPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.jbarcode.util.ImageUtil;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAjaxAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.Attn;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.www.check.controller.CheckCarPrintAjaxController;

/**
 * @author zhangxueliang 打印流程表
 */
public class CheckCarPrintAjaxAction extends TmsAjaxAction {
	private Logger logger = Logger.getLogger(CheckCarPrintAjaxAction.class);
	public static final String SERIAL = "serial";
	public static final String OWNERNAME = "ownerName";

	@Override
	public void process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext uc) throws TmsException {
		
		try {
			logger.debug(this.getClass().getName() + "#execute was called.");
			String serial = request.getParameter("serial");
			
			String ownerType = request.getParameter("ownerType");
			String sourceType = request.getParameter("sourceType");
			String transferPrice = request.getParameter("transferPrcie");
			String cardType = request.getParameter("cardType");
			String checkPrice = request.getParameter("checkPrice");
			String accessCardNo = request.getParameter("accessCardNo");
			String vin = request.getParameter("vin");
			
			String licensePlate = request.getParameter("licensePlate");
			String ownerName =  request.getParameter("ownerName");
			if(StringUtil.isNotBlank(licensePlate)) licensePlate = new String(licensePlate.getBytes("ISO8859-1"), "UTF-8");
			if(StringUtil.isNotBlank(ownerName)) ownerName = new String(ownerName.getBytes("ISO8859-1"), "UTF-8");
			
			String log = "CheckCarPrintAjax,serial:"+serial +" ownerType:"+ownerType+" ownerType:"+sourceType+" sourceType:"+ownerType+" transferPrice:"+transferPrice+" cardType:"+cardType
					+" checkPrice:"+checkPrice+" accessCardNo:"+accessCardNo+" vin:"+vin;
			logger.debug(log);
			//check
			TransferAcceptedInfo accept = new TransferAcceptedInfo();
			accept = accept.getAcceptInfoBySerial(serial, "");
			if(accept!=null && StringUtil.isNotBlank(licensePlate) && !licensePlate.equals(accept.getLicensePlate())){
				TransferAcceptedInfo accept1 = accept.getAcceptInfoBySerial("", licensePlate);
				if(accept1!=null && accept1.getStatus()!=16 && accept1.getStatus()!=0){
					responseValues(response, "【U1037】车辆登记的车牌号码，正在被使用办理过户中，无法重复受理。", TEXT);
					return;
				}
			}
			if(accept!=null && StringUtil.isNotBlank(vin) && !vin.equals(accept.getVin())){
				TransferAcceptedInfo accept1 = accept.findByVinAtGh(vin);
				if(accept1!=null && accept1.getStatus()!=16 && accept1.getStatus()!=0){
					responseValues(response, "【U1038】车辆登记的车架号，正在被使用办理过户中，无法重复受理。", TEXT);
					return;
				}
			}
			
			if(StringUtil.isNotBlank(accessCardNo)){
				Member member = new Member();
				Attn attn = new Attn();
				member = member.getIntegralManagementInfo(accessCardNo);
				attn = attn.getIntegralInfo(accessCardNo);
				if(member==null && attn==null){
					responseValues(response, "【IM010】输入的积分卡不存在。", TEXT);
					return;
				}else{
					if (member != null) {
						if (member.getUserId().equals("2")) {
							responseValues(response, "【U1041】此会员卡被禁用，无法支付。", TEXT);
							return;
						}else if(!StringUtil.isNullOrBlank(member.getVirtualMargin()) && Integer.parseInt(member.getVirtualMargin()) <= 0){
							responseValues(response, "【U1042】卡内过户费余额为零，无法支付。", TEXT);
							return;
						}
					}else if(attn != null){
						if (attn.getUserId().equals("2")) {
							responseValues(response, "【U1041】此会员卡被禁用，无法支付。", TEXT);
							return;
						}else if(attn.getVirtualMargin() <= 0){
							responseValues(response, "【U1042】卡内过户费余额为零，无法支付。", TEXT);
							return;
						}
					}
				}
			}
			
			//
			String remark = "";
			String carLicense = "";
			if(request.getParameter("carLicense")!=null) carLicense = new String(request.getParameter("carLicense").getBytes("ISO8859-1"), "UTF-8");
			if(request.getParameter("remark")!=null) remark = new String(request.getParameter("remark").getBytes("ISO8859-1"), "UTF-8");
			if(request.getParameter("ownerName")!=null) ownerName = new String(request.getParameter("ownerName").getBytes("ISO8859-1"), "UTF-8");

			uc.setAttribute(SERIAL, serial);
			uc.setAttribute(OWNERNAME, ownerName);
			uc.setAttribute("ownerType", ownerType);
			uc.setAttribute("sourceType", sourceType);
			uc.setAttribute("cardType", cardType);
			uc.setAttribute("transferPrice", transferPrice);
			uc.setAttribute("carLicense", carLicense);
			uc.setAttribute("checkPrice", checkPrice);
			uc.setAttribute("remark", remark);
			uc.setAttribute("accessCardNo", accessCardNo);
			uc.setAttribute("licensePlate", licensePlate);
			uc.setAttribute("vin", vin);
			CheckCarPrintAjaxController controller = new CheckCarPrintAjaxController();
			controller.execute(uc);
	       
			TransferAcceptedInfo transferAcceptedInfo = TransferAcceptedInfo.getInstance();
			transferAcceptedInfo = transferAcceptedInfo.getAcceptInfoBySerial(serial,"");
			String lipVi = "";// 车牌号码/VIN码
			String newOwner = "";
			String oldOwner = "";
			if (transferAcceptedInfo.getCarClass()== 1) {
				lipVi = transferAcceptedInfo.getVin();
				newOwner = ownerName;
			} else {
				lipVi = transferAcceptedInfo.getLicensePlate();
				oldOwner = ownerName;
			}
			String background = "";
			if("1".equals(Registry.getConfig(TmsConstants.WWW_LIUCHENG_HOST_KEY)))
			{
				//modify by huangwei 20150725
				background = "<img class='jp-paper-background' src='style/images/memuD.jpg' style='WIDTH:740px; HEIGHT:959px'/>";
			}else{
				background = "<img class='jp-paper-background' src='style/images/menuQ.jpg'  style='WIDTH: 766px; HEIGHT: 1083px'/>";
			}
			// 拼select
			String barPic = createBarcode(request,serial);
			StringBuffer str = new StringBuffer();
			str.append(""
							+ ""+background+""
							+ "<div class='jp-label jp-comp-41'>" + lipVi
							+ "</div>" + "<div class='jp-label jp-comp-42'>"
							+ serial + "</div>"
							+ "<div class='jp-label jp-comp-43'>" + oldOwner + "</div>" +
							"<div class='jp-label jp-comp-45'>"+serial+"</div>" +
							"<div class='jp-label jp-comp-46'>"+transferAcceptedInfo.getLicensePlate()+"</div>" +
							"<div class='jp-label jp-comp-47'>"+ownerName+"</div>" +
							"<div class='jp-label jp-comp-48'>"+DateUtil.getCurrentTimeStr3()+"</div>" +
							"<div class='jp-label jp-comp-51'>"+oldOwner +"</div>" + //WL:20160509
							"<div class='jp-label jp-comp-52'>"+serial +"</div>" + //WL:20160509
							"<div class='jp-label jp-comp-53'>"+transferAcceptedInfo.getLicensePlate() +"</div>" + //WL:20160509
							"<div class='jp-label jp-comp-54'>"+serial +"</div>" + //WL:20160509
							"<div class='jp-label jp-comp-55'>"+transferAcceptedInfo.getLicensePlate() +"</div>" + //WL:20160509
							//barPic
							"<div class='jp-label jp-comp-56'><img src='"+barPic+"'/></div>" + //WL:20160509
							"<div class='jp-label jp-comp-57'><img src='"+barPic+"'/></div>" + //WL:20160509
							"<div class='jp-label jp-comp-58'><img src='"+barPic+"'/></div>" + //WL:20160509
							"<div class='jp-label jp-comp-59'><img src='"+barPic+"'/></div>" + //WL:20160509
							"<div class='jp-label jp-comp-60'><img src='"+barPic+"'/></div>" + //WL:20160509
							
							"<div class='jp-label jp-comp-33'>"+transferAcceptedInfo.getLicensePlate()+"</div>" +
							"<div class='jp-label jp-comp-34'>"+transferAcceptedInfo.getSerial()+"</div>" +
							"<div class='jp-label jp-comp-35'>"+checkPrice+"</div>"); //流程表收费 modify by huangwei
			uc.setAttribute("lcText", str.toString());//for web print
			uc.setAttribute("lcPrintFlag", "1");//for web print
	        //
			responseValues(response, "", TEXT);
			logger.debug(this.getClass().getName() + "#execute was completed.");
		} catch (Exception e) {
			logger.error(e);
		}
	}

	
	private String createBarcode(HttpServletRequest request,String key){
		try {
			JBarcode localJBarcode = new JBarcode(EAN13Encoder.getInstance(), WidthCodedPainter.getInstance(), EAN13TextPainter.getInstance());
			localJBarcode.setEncoder(Code39Encoder.getInstance());
			localJBarcode.setPainter(WideRatioCodedPainter.getInstance());
			localJBarcode.setTextPainter(BaseLineTextPainter.getInstance());
			localJBarcode.setShowCheckDigit(false);
			String paramString = key + ".jpg";
			BufferedImage localBufferedImage = localJBarcode.createBarcode(key);
			String path = request.getSession().getServletContext().getRealPath("/").replace("/tmsweb", "") + Registry.getConfig(TmsConstants.WWW_UPLOAD_TIAO_UPLOAD_KEY);
			File file = new File(path);
			if (!file.exists()) file.mkdirs();
			FileOutputStream localFileOutputStream = new FileOutputStream(path + "/" + paramString);
			ImageUtil.encodeAndWrite(localBufferedImage, "jpeg", localFileOutputStream, 96, 96);
			localFileOutputStream.close();
			return Registry.getConfig(TmsConstants.WWW_UPLOAD_TIAO_UPLOAD_KEY) + "/" + paramString;
		} catch (Exception e) {
			logger.error("createBarcode error", e);
		}
		return "";
	}
	
	
}
